// house_pkg/pages/room/index.ts
Page({
  data: {
    point: '',
    building: '',
    rooms: [],
  },
  onLoad({ point, building }) {
    // 解码参数（处理可能的编码情况）
    const safeDecode = (str) => {
      if (!str) return ''
      try {
        if (str.includes('%25')) {
          return decodeURIComponent(decodeURIComponent(str))
        } else if (str.includes('%')) {
          return decodeURIComponent(str)
        }
        return str
      } catch (e) {
        return str
      }
    }
    const decodedPoint = safeDecode(point)
    const decodedBuilding = safeDecode(building)
    // 创建房间
    this.fake(decodedPoint || point, decodedBuilding || building)
  },
  fake(point, building) {
    // 生成多少个房间（4-8个）
    const size = Math.floor(Math.random() * 5) + 4
    const rooms = []
    let attempts = 0
    // 最多尝试 size * 2 次，避免无限循环
    while (rooms.length < size && attempts < size * 2) {
      attempts++
      // 楼层号生成 1 ~ 20
      const floor = Math.floor(Math.random() * 19) + 1
      // 具体的房间号生成 1 ~ 3
      const No = Math.floor(Math.random() * 2) + 1
      const room = [floor, 0, No].join('')
      // 检测是否有重复的房间号，如果没有重复则添加
      if (!rooms.includes(room)) {
        rooms.push(room)
      }
    }
    // 对房间号进行排序（按楼层和房间号）
    rooms.sort((a, b) => {
      const floorA = parseInt(a.substring(0, a.length - 1))
      const floorB = parseInt(b.substring(0, b.length - 1))
      if (floorA !== floorB) {
        return floorA - floorB
      }
      return parseInt(a) - parseInt(b)
    })
    // 渲染数据
    this.setData({ rooms, point, building })
  },
  // 跳转到表单页面
  goToForm(ev) {
    const { point, building, room } = ev.currentTarget.dataset
    const url = `/house_pkg/pages/form/index?point=${point || ''}&building=${building || ''}&room=${room || ''}`
    wx.navigateTo({ url })
  },
})